import React, { useEffect, useState, useRef } from 'react'
import classNames from 'classnames'

interface Props {
  value: number
  onChange: (value: number) => void
}

const Volume: React.FC<Props> = (props) => {
  const [style, setStyle] = useState({
    width: 0,
    left: 0
  })
  
  const [isDown, setDown] = useState(false)
  const isDownRef = useRef(isDown)
  const volumeWrap = useRef<HTMLDivElement>(null)

  useEffect(() => {
    const info = volumeWrap.current?.getBoundingClientRect()!
    setStyle({
      width: props.value / 100 * info.width,
      left: props.value / 100 * info.width
    })
  }, [props.value])


  useEffect(() => {
    isDownRef.current = isDown
  }, [isDown])

  useEffect(() => {
    const info = volumeWrap.current?.getBoundingClientRect()!

    const mouseup = () => setDown(false)
    const mousemove = (e: MouseEvent) => {
      if (isDownRef.current) {
        let w = e.clientX - info.x
        if (w < 0) w = 0
        if (w > info.width) w = info.width
        setStyle({
          width: w,
          left: w
        })
        props.onChange(Math.floor(w / info.width * 100))
      }
    }
    document.addEventListener('mouseup', mouseup)
    document.addEventListener('mousemove', mousemove)

    return () => {
      document.removeEventListener('mouseup', mouseup)
      document.removeEventListener('mousemove', mousemove)
    }
  }, [])

  return (
    <div className={classNames('volume', { down: isDown })} ref={volumeWrap}>
      <div className="line" style={{ width: style.width }}></div>
      <div className="circle" style={{ left: style.left }} onMouseDown={() => setDown(true)}></div>
    </div>
  )
}

export default Volume